package com.hyy.demo.sample2;

import org.squirrelframework.foundation.component.SquirrelProvider;
import org.squirrelframework.foundation.fsm.*;

/**
 * Created by hyygavin on 2017/9/29.
 */
public class QuickStartSample {

    public static void main(String[] args) {
        // 3. 构建状态机的builder,依据StateMachineSample这个实现类
        UntypedStateMachineBuilder builder = StateMachineBuilderFactory.create(StateMachineSample.class);
        //注册状态跳转时所调用的方法,例如A状态到B状态会执行fromAToB方法
        builder.externalTransition().from("A").to("B").on(FSMEvent.ToB).callMethod("fromTo");
        builder.externalTransition().from("B").to("C").on(FSMEvent.ToC).callMethod("fromTo");
        builder.externalTransition().from("B").to("D").on(FSMEvent.ToD).callMethod("fromTo");
        builder.internalTransition().within("A").on(FSMEvent.InnerA).callMethod("inner");
        builder.internalTransition().within("A").on(FSMEvent.InnerA1).callMethod("inner");
        builder.localTransition().from("A").to("CinA").on(FSMEvent.IntoC);
        builder.localTransition().from("CinA").to("A").on(FSMEvent.OutCA);
        //状态机状态变更为B时触发ontoB方法
        MyAction action = new MyAction("toB");
        builder.onEntry("B").perform(action);
//        builder.defineFinishEvent(FSMEvent.Finish);
//        builder.defineTerminateEvent(FSMEvent.Terminate);
//        builder.defineStartEvent(FSMEvent.Start);
        // 4. 通过builder初始化状态机,初始状态是A
        UntypedStateMachine fsm = builder.newStateMachine("A");
        SCXMLVisitor visitor = SquirrelProvider.getInstance().newInstance(SCXMLVisitor.class);
        fsm.accept(visitor);
        visitor.convertSCXMLFile("d:\\a", true);
        DotVisitor visitor1 = SquirrelProvider.getInstance().newInstance(DotVisitor.class);
        fsm.accept(visitor1);
        visitor1.convertDotFile("d:\\b");

        fsm.start();
        System.out.println(fsm.getCurrentState());
        //通过UntypedStateMachine的fire(event,context)方法来执行触发事件
        //这里通过B事件将状态机的A状态变更为B
        fsm.fire(FSMEvent.InnerA, 1);
        fsm.fire(FSMEvent.InnerA1, 1);
        fsm.fire(FSMEvent.IntoC, 1);
        fsm.fire(FSMEvent.OutCA, 1);
        fsm.fire(FSMEvent.ToB, 2);
        System.out.println("当前状态是：" + fsm.getCurrentState());
        fsm.fire(FSMEvent.ToD, 3);
        System.out.println("当前状态是：" + fsm.getCurrentState());
        // 5. 结束状态机
        fsm.terminate();
        System.out.println(fsm.isTerminated());
    }
}
